package com.jse;

import java.text.MessageFormat;
import java.util.Collection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Strings {
	
	public static boolean isBlank(CharSequence c){return c==null||c.toString().isBlank();}
	public static boolean isNotBlank(CharSequence c){return !isBlank(c);}
	public static boolean isEmpty(CharSequence c) {return c==null||c.isEmpty()||"null".equals(c)||"undefined".equals(c);}
	public static boolean isNotEmpty(CharSequence c) {return !isEmpty(c);}
	public static boolean equals(Object o1,Object o2){
	if(o1==o2)return true;if(o1==null||o2==null)return false;return o1.equals(o2);}
	public static int length(final CharSequence c){return c==null?0:c.length();}
	public static String def(CharSequence c) {return def(c,"");}
	public static String def(CharSequence c,String s) {return isEmpty(c)?s:c.toString();}
	public static boolean isNumeric(String s){return s!=null&&s.length()>0&&s.chars().allMatch(Character::isDigit);}
	
	/** GB 32100-2015XG1-2016 @cs 社会信用码 */
	public static boolean isUSCC(CharSequence cs) {
		var P_USCC = Pattern.compile("^(11|12|13|19|21|29|31|32|33|34|35|39|41|49|51|52|53|59|61|62"
		+ "|69|71|72|79||81|82|91|92|93|A1|A2|N1|N2|N3|N9|Y1)[1-9]{1}[0-9]{5}[0-9A-Z]{9}[0-9A-Z]{1}$");
		return P_USCC.matcher(cs).find();
	}
	
	public static String fmt(String fmt,Object...args) {
		return MessageFormat.format(fmt,args);
	}
	public static boolean isPattern(String s) {return(s.indexOf('*')!=-1||s.indexOf('?')!=-1);}
	protected static final Pattern reUnicode = Pattern.compile("\\\\u([0-9a-zA-Z]{4})");

    public static String unicode(String s) {
            Matcher m = reUnicode.matcher(s);
            StringBuffer sb = new StringBuffer(s.length());
            while (m.find()) {
                m.appendReplacement(sb, Character.toString((char) Integer.parseInt(m.group(1), 16)));
            }
            m.appendTail(sb);
            return sb.toString();
    }
	public static String replace(String s, int i, int j,String x) {
		var s1=s.substring(0,i);
		var s2=x.length()==1?x.repeat(j-i):x;
		var s3=s.substring(j,s.length());
		return s1+s2+s3;
	}
	public static String join(Collection<?> list, String c) {
		StringBuilder sb=new StringBuilder();
		for (var s:list) {
			sb.append(s).append(c);
		}
		if(list.size()>0)
		sb.delete(sb.length()-c.length(),sb.length());
		return sb.toString();
	}
	public static String def(Object o, String d) {if(o==null)return d;var s=o.toString();return isEmpty(s)?d:s;}
}
